#!/bin/bash

#################################################
#########  Aligning functional and structural #############
#################################################

#for more information https://layerfmri.com/2019/02/11/high-quality-registration/ 

#we use a starting matric from ITK-SNAP

antsApplyTransforms --interpolation BSpline[5]       \
                    -d 3                             \
                    -i EPI.nii                       \
                    -r T1.nii                        \
                    -t initial_matrix.txt            \
                    -o registered_EPI.nii


antsApplyTransforms --interpolation BSpline[5]       \
                    -d 3                             \
                    -r EPI.nii                       \
                    -i T1.nii                        \
                    -t [initial_matrix.txt,1]        \
                    -o registered_T1.nii

# we use ANTs for this step
# for furhter warping the below can be applied if needed

antsRegistration --verbose 1 --dimensionality 3 --float 0 \
                    --collapse-output-transforms 1 \
                    --output [registered_,registered_Warped.nii.gz,registered_InverseWarped.nii.gz] \
                    --interpolation BSpline[5] \
                    --use-histogram-matching 0 \
                    -x moma.nii.gz \
                    --winsorize-image-intensities [0.005,0.995] \
                    --initial-moving-transform initial_matrix.txt \
                    --transform Rigid[0.1] \
                    --metric MI[T1.nii,EPI.nii,1,32,Regular,0.25] \
                    --convergence [1000x500x250x0,1e-6,10] \
                    --shrink-factors 12x8x4x2 \
                    --smoothing-sigmas 4x3x2x1vox \
                    --transform SyN[0.1,3,0] \
                    --metric MI[T1.nii,EPI.nii.gz,1,32] \
                    --convergence [100x100x70x50x0,1e-6,10] \
                    --shrink-factors 10x6x4x2x1 \
                    --smoothing-sigmas 5x3x2x1x0vox


#apply the transformation to all functional with better inpterpolatoim
antsApplyTransforms --interpolation BSpline[5]       \
                    -d 3                             \
                    -i EPI.nii                      \
                    -r T1.nii                        \
                    -t registered_1Warp.nii.gz       \
                    -t registered_0GenericAffine.mat \
                    -o registered_applied.nii